package stringtest;


import org.junit.Test;

public class StringTest5 {
    int highLevel = 100000;
    @Test
    public void t1() {
        //常量与常量的拼接结果在常量池，原理是编译期优化
        String s1 = "a"+"b"+"c";
        String s2 = "abc";


        System.out.println(s1==s2);
        System.out.println(s1.equals(s2));
    }

    @Test
    public void t2() {
        //只要有变量的拼接，相当于在堆中 new
        String s1 = "111";
        String s2 = "111222";
        String s3 = s1+"222";
        System.out.println(s3==s2);//false

        String s4 = s3 + "444";
        System.out.println(s4==s3);//flase

        //intern  判断常量是否存在，如果存在返回引用，否则创建并返回引用
        String s5 = s3.intern();
        System.out.println(s5==s2);//true

        String s7 = (s1+"222").intern();
        System.out.println(s7==s2);//true
    }

    @Test
    public void t3(){
        String a = "a";
        String b = "b";
        String s = "ab";
        /*
        * StringBuilder temp = new StringBuilder();
        * temp.append(a);
        * temp.append(b);
        * String c = temp.toString();
        * */
        String c = a+b;
        System.out.println(s==c);
    }

    @Test
    public void t4(){
        final String a = "a";
        final String b = "b";
        String s = "ab";
        /*
         *编译期优化
         * */
        String c = a+b;
        System.out.println(s==c);//true
    }

    @Test
    public void t5(){
        String s = "";
        long start = System.currentTimeMillis();
        for(int i=0;i<highLevel;i++){
            //每次循环都会创建一个StringBuilder,String
            s +="a";
        }
        long end = System.currentTimeMillis();
        System.out.println(end-start);
    }

    /*
    * 可以对其进行优化使用StringBuilder s = new StringBuilder(highLevel);
    * 避免多次对其进行扩容*/
    @Test
    public void t6(){
        StringBuilder s = new StringBuilder("");
        long start = System.currentTimeMillis();
        for(int i=0;i<highLevel;i++){
            s .append("a");
        }
        long end = System.currentTimeMillis();
        System.out.println(end-start);
    }
}
